<template>
  <a-modal
    v-model:visible="modalVisible"
    width="700px"
    :align-center="false"
    title="新增代理角色"
  >
    <template #footer>
      <a-button @click="closeModal">取消</a-button>
      <a-button type="primary" @click="handleSubmit">确定</a-button>
    </template>
    <a-form :rules="rules" :model="form.list" ref="formRef">
      <a-form-item label="代理角色名称">{{ form.list.roleName }} </a-form-item>
      <a-form-item field="agentObjId" label="选择用户">
        <a-select
          :disabled="form.list.id"
          allow-search
          v-model="form.list.agentObjId"
          @change="changeUser"
        >
          <a-option v-for="item in userData" :key="item.id" :value="item.id">{{
            item.name
          }}</a-option>
        </a-select>
      </a-form-item>

      <a-form-item field="menuList" label="选择权限">
        <a-tree-select
          :fieldNames="{
            key: 'id',
            title: 'menuName',
            icon: ''
          }"
          :tree-checkable="true"
          :tree-check-strictly="true"
          v-model="selected"
          :multiple="true"
          :allow-clear="true"
          :allow-search="true"
          :data="tree"
          :filter-tree-node="filterTreeNode"
          @change="changeTreeNode"
        ></a-tree-select>
      </a-form-item>
      <a-form-item label="是否限时">
        <a-switch
          v-model="form.list.isLimitedTime"
          :checked-value="1"
          :unchecked-value="2"
          @change="changeIsLimitedTime"
        />
      </a-form-item>
      <a-form-item v-if="form.list.isLimitedTime === 1" label="失效日期">
        <a-date-picker format="YYYY-MM-DD" v-model="form.list.expiringDate" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import {
  getRoleRelList,
  getPermissionDeduplicationTree
} from '@/apis/roleManagement/index';
import { GetHumanRosterList } from '@/apis/management/human/humanRoster';
import { cloneDeep } from 'lodash';
import { watchEffect } from 'vue';

const emit = defineEmits(['update:visible', 'addAuthAgent']);
const userInfo = JSON.parse(localStorage.getItem('userInfo') as any);
const userData = ref([]);
const formRef = ref();
const initial = ref([]);
function treeToArray(tree) {
  let res = [];
  for (const item of tree) {
    const { children, ...i } = item;
    if (children && children.length) {
      res = res.concat(treeToArray(children));
    }
    res.push(i);
  }
  return res;
}

// 获取人员列表
const getData = async () => {
  const res = await GetHumanRosterList({
    pageNumber: 0,
    pageSize: -1,
    typeName: '4,5,6,9,10,11,12'
  });
  const msg = await getPermissionDeduplicationTree();
  userData.value = res.content.filter((ele) => ele.id !== userInfo.id);
  tree.value = msg.treeMenuList;
  initial.value = treeToArray(msg.treeMenuList);
  console.log(initial.value);
};
getData();
const selected = ref([]);
const mutuallyExclusiveRoleIds = ref([]);
const form = reactive({
  list: {
    id: null,
    agentObjId: null,
    menuList: [],
    isLimitedTime: 2,
    expiringDate: '',
    agentObjName: '',
    roleName: `--代理${userInfo.name}的角色`
  }
});
const validateName = (val: string, callback: any) => {
  if (!val) callback('请选择代理出去的权限');
};
const rules = {
  agentObjId: [{ required: true, message: '请选择代理用户' }],

  menuList: [
    {
      required: true,
      validator: validateName
    }
  ]
};

function filterTreeNode(searchValue, nodeData) {
  return (
    nodeData.menuName.toLowerCase().indexOf(searchValue.toLowerCase()) > -1
  );
}

const changeIsLimitedTime = (e) => {
  if (e === 2) {
    delete form.list.expiringDate;
    console.log(11, form);
  }
};

const props = withDefaults(
  //参数说明
  defineProps<{
    editCompanyForm: any; //修改的数据
    visible: boolean; //是否打开modal
  }>(),
  {
    visible: false
  }
);
// 控制确定取消按钮
const modalVisible = computed({
  //控制visible
  get() {
    return props.visible;
  },
  set() {
    return emit('update:visible', false);
  }
});

const changeUser = (e: number) => {
  form.list.agentObjName = userData.value.filter(
    (item) => item.id === e
  )[0].name;
};

const tree = ref([]);

//取消
const closeModal = () => {
  modalVisible.value = false;
  formRef.value.resetFields;
};

const handleSubmit = async () => {
  const msg = await formRef.value.validate();
  if (!msg) {
    console.log(1, cloneDeep(form.list));
    if (!form.list.id) emit('addAuthAgent', cloneDeep(form.list), 'add');
    else emit('addAuthAgent', cloneDeep(form.list), 'edit');
    closeModal();
  }
};

// const getTree = (data:any) =>{
//   data.forEach(item=>{
//     if()
//   })
// }

const changeTreeNode = (e) => {
  console.log(e, initial.value);

  form.list.menuList = [];
  if (!e) return;
  e.forEach((item) => {
    const index = initial.value.findIndex((ele) => ele.id === item);
    if (index > -1) {
      form.list.menuList.push({
        ...initial.value[index]
      });
    }
  });
  console.log(form.list.menuList);
};

const replaceBeforeDelimiter = (str, delimiter, newContent) => {
  let parts = str.split(delimiter);
  if (parts.length > 1) {
    parts[0] = newContent;
    return parts.join(delimiter);
  }
  return str; // 如果没有找到分隔符，则返回原字符串
};

watchEffect(() => {
  if (form.list.agentObjName) {
    form.list.roleName = replaceBeforeDelimiter(
      form.list.roleName,
      '代理',
      form.list.agentObjName
    );
  }
});

const getEdit = () => {
  form.list = Object.assign(form.list, props.editCompanyForm);
  form.list.menuList.forEach((ele) => {
    selected.value.push(ele.id);
  });
  console.log('edit', props.editCompanyForm, form.list);
};

onMounted(() => {
  if (props.editCompanyForm.id) {
    getEdit();
  }
});
</script>
